<script setup>
import { onMounted, defineEmits, ref } from 'vue'
import { INIT_YAML, MONACO_VS_PATH } from '/src/constants'
import { yaml2pac } from '/src/utils'

let instance
const container = ref()
const emit = defineEmits(['value'])

onMounted(() => {
  window.require.config({ paths: { vs: MONACO_VS_PATH } })

  chrome.storage.sync.get('yaml', (data) => {
    const code = data.yaml || INIT_YAML

    const model = monaco.editor.createModel(
      code,
      'yaml',
      monaco.Uri.parse('json://grid/settings.json')
    )

    instance = monaco.editor.create(container.value, {
      model,
      tabSize: 2,
      automaticLayout: true,
      scrollBeyondLastLine: false,
      minimap: {
        enabled: false
      },
      scrollbar: {
        vertical: 'visible',
        horizontal: 'visible',
      },
    })

    instance.onDidChangeModelContent(async () => {
      const value = instance.getValue()
      chrome.storage.sync.set({ yaml: value })
      emit('value', await yaml2pac(value))
    })
  })
})
</script>

<template>
  <div class="editor-wrapper">
    <div class="editor" ref="container"></div>
  </div>
</template>

<style>
.editor-wrapper {
  border: 1px solid #ececec;
}
.editor {
  height: 550px;
}
</style>
